package com.cool.reggie.core.exception;

import com.cool.reggie.utils.ResultData;
import lombok.extern.slf4j.Slf4j;
import org.apache.ibatis.javassist.NotFoundException;
import org.springframework.dao.DuplicateKeyException;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

import java.sql.SQLIntegrityConstraintViolationException;

/**
 * @Author ifredomvip@gmail.com
 * @Date 2022/7/4 14:37
 * @Version 1.0.0
 * @Description
 **/
@ControllerAdvice(annotations = {RestController.class, Controller.class})
@ResponseBody
@Slf4j
public class GlobalExceptionHandle {

    /**
     * 处理异常
     *
     * @param e e
     * @return {@link ResultData}
     */
    @ExceptionHandler(DuplicateKeyException.class)
    public ResultData handleException(DuplicateKeyException e) {
        log.info("DuplicateKeyException Exception： " + e.getMessage());
        return ResultData.error("数据库中已存在该数据");
    }

    /**
     * 处理没有发现异常
     *
     * @param e e
     * @return {@link ResultData}
     */
    @ExceptionHandler(NotFoundException.class)
    public ResultData handleNotFoundException(NotFoundException e){
        log.info("NotFoundException Exception： " + e.getMessage());
        return ResultData.error("数据不存在");
    }

    /**
     * 处理自定义业务异常
     *
     * @param e e
     * @return {@link ResultData}
     */
    @ExceptionHandler(CustomException.class)
    public ResultData handleCustomException(Exception e){
        log.info("CustomException ===>" + e.getMessage());
        return ResultData.error(e.getMessage());
    }

    /**
     * 处理所有异常
     *
     * @param e e
     * @return {@link ResultData}
     */
    @ExceptionHandler(Exception.class)
    public ResultData handleAllException(Exception e){
        log.info("Exception ===>" + e.getMessage());
        return ResultData.error("未知错误");
    }

}
